﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Web.Script.Serialization;
using System.Web;

namespace Karasoft.Common
{
    public class WhatsAppRequest
    {
        private HttpWebRequest request;
        private string url;
        public WhatsAppRequest(string key, string cc, string number, string msg)
        {
            msg = HttpUtility.UrlEncode(msg);
            number = HttpUtility.UrlEncode(number);
            cc = HttpUtility.UrlEncode(cc);
            key = HttpUtility.UrlEncode(key);
            url = string.Format("http://api.whatsapp-api.com/connector/auth?key={0}&cc={1}&number={2}&msg={3}", key, cc, number, msg);
        }

        public WhatsAppResult GetResponse()
        {
            string json;
            Encoding encode = Encoding.GetEncoding("UTF-8");
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            using (WebResponse wr = request.GetResponse())
            {
                using (StreamReader myStreamReader = new StreamReader(wr.GetResponseStream(), encode))
                {
                    json = myStreamReader.ReadToEnd();
                }
            }
            return (new JavaScriptSerializer()).Deserialize<WhatsAppResult>(json);
        }
    }

    [DataContract]
    public class WhatsAppResult
    {
        [DataMember(Name = "result", Order = 0, IsRequired = true)]
        public string Result
        {
            get;
            set;
        }

        [DataMember(Name = "reason", Order = 1, IsRequired = false)]
        public string Reason
        {
            get;
            set;
        }

        public override string ToString()
        {
            if (Result != "1")
            {
                return "Result: \"" + Result + "\". Reason: \"" + Reason + "\"";
            }
            else
            {
                return "Result: \"" + Result + "\".";
            }
        }
    }
}
